# -*- coding: utf-8 -*-
import cgi
import os
import sys
import datetime
import time
import wsgiref.handlers
import string

from control import *

from time import strftime, localtime 
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
from loginTool import login_required
from models import Images

class PhotoLib(db.Model):#//图库包含图片表
      photoLibCode = db.IntegerProperty()#//图库编号
      photoLibName = db.StringProperty(multiline=True)#//图库名
      date = db.DateTimeProperty(auto_now_add=True)#//上次更新时

class PhotoLib_Photo(db.Model):#//图库包含图片表
      indexNo = db.IntegerProperty()#//图片排序号
      photoLibCode = db.StringProperty(multiline=True)#//图库编号
      photoCode = db.StringProperty(multiline=True)#//图片编号
      status =db.StringProperty(multiline=True) #//图片状态 1=改变图片名字、2=已删、3=增加
      lastUpdateTime = db.DateTimeProperty(auto_now_add=True)#//上次更新时间

class PublicPage(webapp.RequestHandler):
  def render(self, template_file, template_value):
      path = os.path.join(os.path.dirname(__file__), template_file)
      self.response.out.write(template.render(path, template_value))

class PhotoLibList(PublicPage):
  @login_required
  def get(self):
      searchType = self.request.get('searchType')#'searchType‘不存在是返回的不是None，而是''空字符
      if searchType=='':#
            photoLibs = db.GqlQuery("SELECT * FROM PhotoLib ORDER BY photoLibName ASC ")#
      else:#
            photoLibs = db.GqlQuery("SELECT * FROM PhotoLib WHERE photoLibName=:1",searchType)#
      template_values = {'photoLibs':photoLibs,}
      self.render('template/photoLid/photoLibList.html',template_values)
#      self.render('html/photoLidManage/photoLibList.html',template_values)
  @login_required
  def post(self):#
      searchType = self.request.get('searchType')#
      self.redirect('/photoLibList?searchType=%s' %searchType)#
             
class PhotoLibAdd(PublicPage):
  @login_required
  def get(self):
      self.render('template/photoLid/photoLibAdd.html',{})#本地上运行用这个
#      self.render('html/photoLidManage/photoLibAdd.html',{})#本地上运行用这个
  @login_required
  def post(self):
      greeting = PhotoLib()
      greeting.photoLibCode = string.atoi(getTimeIndex())
      greeting.photoLibName = self.request.get('photoLibName')
      greeting.put()
      self.redirect('/photoLibList')

class PhotoLibDelete(PublicPage):
  @login_required
  def get(self):
      photoLibCode=self.request.get('photoLibCode')
      photoLibs=db.GqlQuery("SELECT * FROM PhotoLib WHERE photoLibCode=:1",string.atoi(photoLibCode))#将字符转为数字
      if (photoLibs):
            for photoLib in photoLibs:
                  db.delete(photoLib)
      self.redirect('/photoLibList')

class SearchPhoto(PublicPage):
  @login_required
  def post(self):
      radio = self.request.get('radio')
      searchType = self.request.get('searchType')
      photoLibCode = self.request.get('photoLibCode')
      photoLibName = self.request.get('photoLibName')
      self.redirect('/addPhotoToLib?radio=%s&searchType=%s&photoLibCode=%s&photoLibName=%s' %(radio,searchType,photoLibCode,photoLibName))

class AddPhotoToLib(PublicPage):
  @login_required
  def get(self):
      radio = self.request.get('radio')
      searchType = self.request.get('searchType')
      photoLibCode = self.request.get('photoLibCode')
      photoLibName = self.request.get('photoLibName')
      photoLib_Photos = db.GqlQuery("SELECT * FROM PhotoLib_Photo WHERE photoLibCode=:1" ,photoLibCode)
      pLibList=[]
      LibList = []
      if (searchType ==''):
            images=db.GqlQuery("SELECT * FROM Images")
      else:
            if radio == 'imageId':
                  images=db.GqlQuery("SELECT * FROM Images WHERE photoCode>=:1 AND photoCode<=:2",searchType,u""+searchType+"" + u"\ufffd")
            if radio == 'imageName':
                  images=db.GqlQuery("SELECT * FROM Images WHERE name>=:1 AND name<=:2",searchType,u""+searchType+"" + u"\ufffd")
            
      for photoLib_Photo in photoLib_Photos:
            pLibList.append(photoLib_Photo)
      for image in images:
            flag = 0     
            for pList in pLibList:
                  if pList.photoCode==image.photoCode:
                        flag = 1
            if flag == 0:
                  LibList.append(image)
      images=LibList           
      template_values = {'photoLibCode':photoLibCode,"photoLibName":photoLibName,"images":images,"radio":radio,"searchType":searchType,"photoLibCode":photoLibCode,"photoLibName":photoLibName}
      self.render('template/photoLid/addPhotoToLib.html',template_values)#本地上运行用这个
#      self.render('html/photoLidManage/addPhotoToLib.html',template_values)#本地上运行用这个
  @login_required
  def post(self):
      photoLib_Photo = PhotoLib_Photo()
      photoLibCode = photoLib_Photo.photoLibCode = self.request.get('photoLibCode')
      photoCode = photoLib_Photo.photoCode = self.request.get('photoCode')
      photoLib_Photo.indexNo = string.atoi(getTimeIndex());
      photoLib_Photo.status = '1'
      photoLib_Photo.put()
      photoLibName = self.request.get('photoLibName')
#      photoLibs = db.GqlQuery("SELECT * FROM PhotoLib WHERE photoLibCode=:1",string.atoi(photoLibCode))
#      for photoLib in photoLibs:
#            if photoLib.photoLibCode:
#                  photoLib.date=datetime.datetime.now()
#                  db.put(photoLib)
      self.redirect('/photoLib_PhotoList?photoLibCode=%s&photoLibName=%s' %(photoLibCode,photoLibName))

class PhotoLib_PhotoList(PublicPage):

  @login_required
  def get(self):
      photoLibCode = self.request.get('photoLibCode')
      photoLibName = self.request.get('photoLibName')
#      photoLib_Photoslist = PhotoLib_Photo.all().filter('photoLibCode=', photoLibCode).order("photoCode")
      photoLib_Photoslist = db.GqlQuery("SELECT * FROM PhotoLib_Photo WHERE photoLibCode=:1 ORDER BY lastUpdateTime  ASC",photoLibCode)
      photoLib_Photos=[]
      for p in photoLib_Photoslist:
          img=Images.get_by_id(int(p.photoCode))
          if img:
              p.imageName=img.name
          else:
              p.imageName="No Image"
          photoLib_Photos.append(p)
      template_values = {'photoLib_Photos':photoLib_Photos,'photoLibCode':photoLibCode,'photoLibName':photoLibName}
      self.render('template/photoLid/photoLib_PhotoList.html',template_values)#本地上运行用这个
#      self.render('html/photoLidManage/photoLib_PhotoList.html',template_values)#本地上运行用这个
        
class PhotoLib_PhotoDelete(PublicPage):
  @login_required
  def get(self):
      indexNo = self.request.get('indexNo')
      photoLibCode = self.request.get('photoLibCode')
      photoLib_Photos = db.GqlQuery("SELECT * FROM PhotoLib_Photo WHERE indexNo=:1",string.atoi(indexNo))
#      photoLibs = db.GqlQuery("SELECT * FROM PhotoLib WHERE photoLibCode=:1",string.atoi(photoLibCode))
#      for photoLib in photoLibs:
#            if photoLib.photoLibCode:
##                  photoLib.date=datetime.datetime.now()
#                  db.put(photoLib)
      if photoLib_Photos:
            for photoLib_Photo in photoLib_Photos:
                  db.delete(photoLib_Photo)
                  self.redirect('/photoLib_PhotoList?photoLibCode=%s' %photoLibCode)
      
class PhotoLib_PhotoUpdate(PublicPage):
  @login_required
  def get(self):
      indexNo = self.request.get('indexNo')#3
      photoLib_Photos = db.GqlQuery("SELECT * FROM PhotoLib_Photo WHERE indexNo=:1",string.atoi(indexNo))
      template_values = {'photoLib_Photos':photoLib_Photos,}
      self.render('template/photoLid/photoLib_PhotoUpdate.html',template_values)
#      self.render('html/photoLidManage/photoLib_PhotoUpdate.html',template_values)
  @login_required
  def post(self):
      photoLibCode = self.request.get('photoLibCode')#1
      photoCode = self.request.get('photoCode')#2
      indexNo = self.request.get('indexNo')#3
      photoLib_Photos = db.GqlQuery("SELECT * FROM PhotoLib_Photo WHERE indexNo=:1",string.atoi(indexNo))
      for photoLib_Photo in photoLib_Photos:
            photoLib_Photo.status = self.request.get('replyType')#4更新图片状态
            photoLib_Photo.lastUpdateTime=datetime.datetime.now()#5更新时间
            db.put(photoLib_Photo)
      p=PhotoLib.all().filter("photoLibCode=",int(photoLibCode)).fetch(1)
      if len(p)==1:
          pn=p[0].photoLibName
      else:
          pn='No Name'
      self.redirect('/photoLib_PhotoList?photoLibCode=%s&photoLibName=%s' %(photoLibCode,pn))     
